<template>
  <a-space
    align="center"
    style="width: 100%; justify-content: center; margin-bottom: 16px"
  >
    <!-- 搜索表单 -->
    <a-form
      :model="formSearchParams"
      layout="inline"
      @submit="doSearch"
    >
      <a-form-item field="userName" label="用户名">
        <a-input
          allow-clear
          v-model="formSearchParams.userName"
          placeholder="请输入用户名"
        />
      </a-form-item>
      <a-form-item field="userProfile" label="用户简介">
        <a-input
          allow-clear
          v-model="formSearchParams.userProfile"
          placeholder="请输入用户简介"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
        <a-button type="primary" html-type="submit">搜索</a-button>

        <!-- 新增按钮 -->
        <a-button type="primary" @click="openModal('add')">新增用户</a-button>
        </a-space>
      </a-form-item>
    </a-form>


  </a-space>

  <!-- 列表 -->
  <a-table
    :columns="columns"
    :data="dataList"
    :pagination="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total
    }"
    @page-change="onPageChange"
  >
    <template #userAvatar="{ record }">
      <a-image width="64" :src="record.userAvatar" />
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <!-- 修改按钮 -->
        <a-button type="text" @click="openModal('edit', record)">修改</a-button>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>

  <!-- 新增/编辑对话框 -->
  <a-modal
    v-model:visible="modalVisible"
    :title="modalType === 'add' ? '新增用户' : '编辑用户'"
    @ok="handleModalOk"
    :confirm-loading="modalLoading"
  >
    <a-form :model="modalForm" label-align="left" auto-label-width>
      <a-form-item field="userAccount" label="账号" :required="true">
        <a-input v-model="modalForm.userAccount" />
      </a-form-item>
      <a-form-item field="userAvatar" label="头像 URL">
        <a-space align="center">
          <!-- 文本框 -->
          <a-input
            v-model="modalForm.userAvatar"
            placeholder="请输入或上传头像链接"
            style="width: 240px"
          />
          <!-- 上传按钮 -->
          <a-upload
            action="http://106.54.212.16:8101/api/file/upload"
            :data="{ biz: 'user_avatar' }"
            accept="image/*"
            :with-credentials="true"
            :show-upload-list="false"
            @success="handleAvatarUploadSuccess"
            @error="handleAvatarUploadError"
          >
            <a-button type="outline" size="small">上传</a-button>
          </a-upload>
        </a-space>
        <!-- 预览 -->
        <div v-if="modalForm.userAvatar" style="margin-top: 8px">
          <a-image :src="modalForm.userAvatar" width="80" height="80" />
        </div>
      </a-form-item>
      <a-form-item field="userName" label="用户名">
        <a-input v-model="modalForm.userName" />
      </a-form-item>
      <a-form-item field="userRole" label="角色">
        <a-select v-model="modalForm.userRole" :options="roleOptions" />
      </a-form-item>
      <a-form-item field="userProfile" label="简介">
        <a-textarea v-model="modalForm.userProfile" rows="3" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect } from "vue";
import dayjs from "dayjs";
import message from "@arco-design/web-vue/es/message";
import {
  listUserByPageUsingPost,
  deleteUserUsingPost,
  addUserUsingPost,
  updateUserUsingPost,
} from "@/api/userController";
import API from "@/api";

// --- 搜索 & 列表状态 ---
const formSearchParams = ref<Partial<API.UserQueryRequest>>({});
const initSearchParams = { current: 1, pageSize: 10 };
const searchParams = ref<Partial<API.UserQueryRequest>>({ ...initSearchParams });
const dataList = ref<API.User[]>([]);
const total = ref(0);

async function loadData() {
  const res = await listUserByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败：" + res.data.message);
  }
}

function doSearch() {
  searchParams.value = { ...initSearchParams, ...formSearchParams.value };
}

function onPageChange(page: number) {
  searchParams.value = { ...searchParams.value, current: page };
}

function doDelete(record: API.User) {
  if (!record.id) return;
  deleteUserUsingPost({ id: record.id }).then((res) => {
    if (res.data.code === 0) loadData();
    else message.error("删除失败：" + res.data.message);
  });
}

// 自动加载
watchEffect(loadData);

// --- 新增/编辑对话框状态 ---
const modalVisible = ref(false);
const modalLoading = ref(false);
const modalType = ref<"add" | "edit">("add");
const modalForm = reactive<API.UserAddRequest & Partial<API.UserUpdateRequest>>({
  userAccount: "",
  userAvatar: "",
  userName: "",
  userRole: "",
  userProfile: "",
  id: undefined,
});
const roleOptions = [
  { label: "管理员", value: "admin" },
  { label: "普通用户", value: "user" },
];

function openModal(type: "add" | "edit", record?: API.User) {
  modalType.value = type;
  if (type === "edit" && record) {
    Object.assign(modalForm, record); // 将 record 的字段映射到 form
  } else {
    // 清空表单
    Object.assign(modalForm, {
      id: undefined,
      userAccount: "",
      userAvatar: "",
      userName: "",
      userRole: "",
      userProfile: "",
    });
  }
  modalVisible.value = true;
}

async function handleModalOk() {
  modalLoading.value = true;
  try {
    if (modalType.value === "add") {
      await addUserUsingPost(modalForm as API.UserAddRequest);
      message.success("新增成功");
    } else {
      await updateUserUsingPost(modalForm as API.UserUpdateRequest);
      message.success("修改成功");
    }
    modalVisible.value = false;
    loadData();
  } catch (e: any) {
    message.error("操作失败：" + e.message);
  } finally {
    modalLoading.value = false;
  }
}

// 表格列定义
const columns = [
  { title: "账号", dataIndex: "userAccount" },
  { title: "用户名", dataIndex: "userName" },
  { title: "头像", dataIndex: "userAvatar", slotName: "userAvatar" },
  { title: "简介", dataIndex: "userProfile" },
  { title: "角色", dataIndex: "userRole" },
  { title: "创建时间", dataIndex: "createTime", slotName: "createTime" },
  { title: "更新时间", dataIndex: "updateTime", slotName: "updateTime" },
  { title: "操作", slotName: "optional" },
];

// 上传成功
function handleAvatarUploadSuccess(file: any) {
  const res = file.response as { code: number; data: string; message: string }
  if (res.code === 0) {
    modalForm.userAvatar = res.data
  } else {
    message.error('头像上传失败：' + res.message)
  }
}

// 上传失败
function handleAvatarUploadError(err: Error) {
  message.error('头像上传出错：' + err.message)
}
</script>
